<?php
/**
 * Created by PhpStorm.
 * User: 86188
 * Date: 2021/1/14
 * Time: 14:24
 */

namespace app\admin\controller;


use app\service\billService;
use app\service\roominfoService;
use invoice\Api;
use think\facade\Db;
use think\facade\View;

class Invoicedirect extends Common
{
    public function test(){
        $str='{"community_id":"ARYYP7RQA3301","buyerName":"1","buyerPhone":"1","buyerTaxNum":"","buyerTel":"","buyerAddress":"","buyerAccount":"","invoiceDetails":[{"goodsName":"物业费","specType":"1","unit":"期","num":"1","price":"2","taxrate":"0.06"}]}';
        $str=json_encode($str);
        var_dump($str);
    }
    public function detailsadd(){
        $costtype=Db::table("costtype")->distinct("type")->select()->toArray();
        //var_dump($costtype);
        return View::fetch();
    }
    //发票列表
    public function invoicelist(){
        //查询小区信息
        $com = $this->pidTokenId();

        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        View::assign('communitylist',$communitylist);

        //搜索时
        $data = request()->get();
        $where=array();
        if (!empty($data)){
            if(!empty($data["community_id"])){
                $where["a.community_id"]=$data["community_id"];
            }
            if(!empty($data["invoice_type"])){
                $where["a.invoice_type"]=$data["invoice_type"];
            }
        }

        $page = request()->has('page') ? request()->get('page') : 1;
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        //var_dump($export);
        //查询账单数据
        $invoicelist = Db::table("invoicedirect")
            ->alias("a")
            ->join("community c","a.community_id=c.community_id")
            ->where("a.community_id","in",$community_id)
            ->where($where)
            ->field("a.*,c.community_name")

            ->order("id desc")
            ->paginate(20, false, [
                'page'  =>  $page,
                'query' =>  $where
            ]);
        //查询账单条数
        $number = Db::table("invoicedirect")
            ->alias("a")
            ->where("a.community_id","in",$community_id)
            ->where($where)
            ->count();

        View::assign('list',$invoicelist);

        View::assign('number',$number);

        //var_dump($data);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch('invoice_list');
    }

    //发票内容修改
    public function invoiceEdit(){
        if(request()->isPost()){
            $info=request()->post("data");
            //Log::write($info,"yangmsg");

            $info=html_entity_decode($info);
            $info=json_decode($info,true);

            $invoicedirect_id=$info["invoicedirect_id"];
            $invoicedirect['community_id']=$info["community_id"];
            $invoicedirect['buyerName']=$info["buyerName"];
            $invoicedirect['buyerPhone']=$info["buyerPhone"];
            $invoicedirect['buyerTaxNum']=$info["buyerTaxNum"];
            $invoicedirect['buyerTel']=$info["buyerTel"];
            $invoicedirect['buyerAddress']=$info["buyerAddress"];
            $invoicedirect['buyerAccount']=$info["buyerAccount"];

            $invoiceDetails=$info["invoiceDetails"];

            Db::startTrans();
            $pay_money=0;
            try {
                $id=Db::table('invoicedirect')->where("id",$invoicedirect_id)->update($invoicedirect);
                Db::table('invoicedirectdetails')->where("invoicedirect_id",$invoicedirect_id)->delete();
                foreach ($invoiceDetails as $value){
                    $tax=round($value["price"]*$value["num"]*$value["taxRate"],2);
                    $pay_money=$pay_money+round($value["price"]*$value["num"],2);
                    $value["tax"]=$tax;
                    $value["invoicedirect_id"]=$invoicedirect_id;
                    Db::table('invoicedirectdetails')->insert($value);
                }
                Db::table('invoicedirect')->where("id",$invoicedirect_id)->update([
                    "pay_money"=>$pay_money
                ]);
                // 提交事务
                Db::commit();
                return json(["errorCode"=>"0"]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(["errorCode"=>"error","errmsg"=>$e->getMessage()]);
            }
            return json(["errorCode"=>"0"]);
        }else{
            $id=request()->get("id");
            $invoiceinfo=Db::table("invoicedirect")->where("id",$id)->find();
            if(empty($invoiceinfo)){
                return "发票内容不存在";
            }
            View::assign("invoiceinfo",$invoiceinfo);

            //查询小区信息
            $com = $this->pidTokenId();
            $where['community_id'] = array('in',$com['community_id']);
            $communitylist = (new roominfoService())->communityList($where);
            View::assign('communitylist',$communitylist);
            $detaillist=Db::table("invoicedirectdetails")->where("invoicedirect_id",$id)->select()->toArray();
            $str="";
            foreach ($detaillist as $values){

                $str=$str."{\"goodsName\":\"".$values["goodsName"]."\",\"specType\":\"".$values["specType"]."\",\"unit\":\"".$values["unit"]."\",\"num\":\"".$values["num"]."\",\"price\":\"".$values["price"]."\",\"taxRate\":\"".$values["taxRate"]."\"},";
            }
            $str=substr($str,0,strlen($str)-1);
            $str=$str."";


            View::assign("str",$str);

            return View::fetch("invoice_edit");
        }

    }
    //发票导出
    public function invoiceExportExcel(){
        $export=request()->param("export");
        //Log::write(request()->param(),"账单导出参数");
        $where = str_replace("|","\"",$export);
        $where=json_decode($where,true);
        //var_dump($where);die;
        //查询小区信息
        $com = $this->pidTokenId();

        $whe['community_id'] = array('in',$com['community_id']);

        $community_id = $com['community_id'];

        //查询账单数据
        $invoicelist = Db::table("invoicedirect")
            ->alias("a")
            ->join("community c","a.community_id=c.community_id")
            ->where("a.community_id","in",$community_id)
            ->where($where)
            ->field("a.*,c.community_name")

            ->order("id desc")
            ->select()->toArray();
        //查询账单条数
        $number = Db::table("invoicedirect")
            ->alias("a")
            ->where("a.community_id","in",$community_id)
            ->where($where)
            ->count();

        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '小区名称')
            ->setCellValue('B1', '发票抬头')
            ->setCellValue('C1', '税号')
            ->setCellValue('D1', '含税金额')
            ->setCellValue('E1', '发票号码')
            ->setCellValue('F1', '发票类型')
            ->setCellValue('G1', '开票时间');

        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数

        for ($i = 2; $i <= $number+1; $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $invoicelist[$i-2]["community_name"]);


            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $invoicelist[$i-2]["buyerName"]);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $invoicelist[$i-2]["buyerTaxNum"]);

            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $invoicelist[$i-2]['pay_money']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $invoicelist[$i-2]['invoiceNum']);
            $invoice_type="蓝票";
            if($invoicelist[$i-2]["invoice_type"]=="2")
            {
                $invoice_type="红票";
            }
            if($invoicelist[$i-2]["invoice_type"]=="3")
            {
                $invoice_type="未开票";
            }
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $invoice_type);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $invoicelist[$i-2]["invoice_time"]);


        }
        $objPHPExcel->getActiveSheet()->setTitle('发票信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        header('Content-Disposition: attachment;filename="发票信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007"); //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件

    }
    //删除
    public function del(){
        $id=request()->param("id");
        Db::startTrans();
        try {

            Db::table('invoicedirect')->where("id",$id)->delete();
            Db::table('invoicedirectdetails')->where("invoicedirect_id",$id)->delete();
            // 提交事务
            Db::commit();

            return json(["success"=>"删除成功"]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(["error"=>$e->getMessage()]);
        }
    }

    //发票冲红
    public function Cancellation(){
        //判断是否存在该数据
        $id = request()->param('id');
        //var_dump($id);die;
        $invoicedirect = Db::table("invoicedirect")->where("id",$id)->find();
        if(empty($invoicedirect)){
            return json(['error' => '发票信息不存在']);
            return '发票信息不存在';
        }
        if($invoicedirect["invoice_type"]=="2"){
            return json(['error' => '已冲红']);
        }


        $invoicedirectdetails=Db::table("invoicedirectdetails")->where("invoicedirect_id",$id)->select()->toArray();
        $invoiceDetail=array();

        $community_id=$invoicedirect["community_id"];


        //判断房号是否相同
        foreach($invoicedirectdetails as $value){

            $goodsCode=Db::name('costtype')->where('type',$value['goodsName'])->where("goodsCode","<>","0")->value('goodsCode');;
            if(empty($goodsCode)){
                $goodsCode='';
            }

            $invoiceDetail[] = "{'goodsName':'{$value['goodsName']}','specType':'{$value['specType']}','unit':'{$value['unit']}','num':'-{$value['num']}','price':'{$value['price']}','withTaxFlag':'1','taxRate':'{$value['taxRate']}','tax':'-{$value['tax']}','goodsCode':'{$goodsCode}'}";




        }

        $invoiceDetail = implode(',', $invoiceDetail);


        $communityinfo = (new billService())->communityName($community_id);
        $propertyinfo = (new billService())->propertyInfo($communityinfo['property_id']);
        $serviceinfo = (new billService())->serviceInfo($propertyinfo['service_id']);
        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
        if($second < 86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{

            $res = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
            $res=json_decode($res,true);
            if($res["errCode"]=="0"){
                $access_token=$res["fp_access_token"];
            }else{
                return json(["error"=>$res["errormsg"]]);
            }
        }
        $invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time();


        $appKey = $serviceinfo["fp_app_key"];
        $appSecret = $serviceinfo["fp_app_secret"];
        $token = $access_token;// please store the token and refresh it before expired
        $taxnum = $serviceinfo["fp_saler_tax_num"];
        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain

        $method2 = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
        $senid2 = uniqid(); // generate your meaningful senid
        $body2 = json_encode(
            array(
                "invoiceSerialNum" => array($invoicedirect['invoice_serial_num'])
            )
        );

        $result2 = Api::sendPostSyncRequest($url, $senid2, $appKey, $appSecret, $token, $taxnum, $method2, $body2);
        $result2 = json_decode($result2, true);
        if($result2['code'] != 'E0000'){
            return json(['error' => $result2['describe']]);
        }
        //var_dump($result2);die;
        $invoiceCode = $result2['result'][0]['invoiceCode'];
        $invoiceNum = $result2['result'][0]['invoiceNum'];


        $method = "nuonuo.electronInvoice.requestBilling"; // change to your method
        $senid = uniqid(); // generate your meaningful senid

        $invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time();
        $buyerName=$invoicedirect["buyerName"];
        $buyerPhone=$invoicedirect["buyerPhone"];
        //$buyerPhone="188561510";
        $fp_saler_tax_num=$serviceinfo['fp_saler_tax_num'];
        $salerAddress=$serviceinfo['address'];
        $salerTel=$serviceinfo['phone'];
        $salerAddress=$serviceinfo['address'];
        $salerAccount=$serviceinfo['fp_saler_account'];
        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"2\",
            \"invoiceCode\": \"$invoiceCode\",
            \"invoiceNum\": \"$invoiceNum\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"\"
            }
        }";



        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        var_dump($result);

        $result = json_decode($result, true);
        if($result['code'] == 'E0000'){
            $invoiceSerialNum = $result['result']['invoiceSerialNum'];
            Db::table("invoicedirect")
                ->where("id",$id)
                ->update([
                    'invoice_serial_num_red'=>$invoiceSerialNum,
                    'invoice_type'=>2
                ]);

            return json(["success"=>'冲红成功']);
        }else{
            return json(['error' => $result['describe']]);
        }
    }

    //红票查看
    public function checkInvoiceRed()
    {
        $id = request()->param('id');

        $invoicedirect = Db::table("invoicedirect")->where("id",$id)->find();

        if(!empty($invoicedirect["invoiceFileUrlRed"])){

            return $this->redirect($invoicedirect['invoiceFileUrlRed']);
        }

        //return $this->redirect($billinvoice['invoiceFileUrl']);
        //判断房号是否相同
        $communityinfo = (new billService())->communityName($invoicedirect['community_id']);

        $propertyinfo = (new billService())->propertyInfo($communityinfo['property_id']);

        $serviceinfo = (new billService())->serviceInfo($propertyinfo['service_id']);

        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
        if($second < 86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{

            //return $access_token;
            $res = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
            $res=json_decode($res,true);
            if($res["errCode"]=="0"){
                $access_token=$res["fp_access_token"];
            }else{
                return json(["error"=>$res["errormsg"]]);
            }
        }

        $timestmp = time();

        $appKey = $serviceinfo["fp_app_key"];
        $appSecret = $serviceinfo["fp_app_secret"];
        $token = $access_token;// please store the token and refresh it before expired
        $taxnum = $serviceinfo["fp_saler_tax_num"];

        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        $method = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
        $senid = uniqid(); // generate your meaningful senid
        $body = json_encode(
            array(
                "invoiceSerialNum" => array($invoicedirect['invoice_serial_num_red'])
            )
        );

        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);


        $result = json_decode($result, true);


        if($result['code'] == 'E0000'){

            $info["invoiceNumRed"]=$result["result"][0]['invoiceNum'];
            $info["invoiceFileUrlRed"]=$result["result"][0]['invoiceFileUrl'];
            Db::table("invoicedirect")->where("id",$id)->update($info);


            return $this->redirect($result['result'][0]['invoiceFileUrl']);
        }else{
            return json(['error' => $result['describe']]);
        }
        return $res;
    }

    //开票
    public function invoice(){
        $id=request()->param("id");
        $invoicedirect=Db::table("invoicedirect")->where("id",$id)->find();
        if($invoicedirect["invoice_type"]!="3"){
            return json(["error"=>"不能重复开票"]);
        }

        $invoicedirectdetails=Db::table("invoicedirectdetails")->where("invoicedirect_id",$id)->select()->toArray();
        $invoiceDetail=array();

        $community_id=$invoicedirect["community_id"];
        $taxmoney=0;

        foreach ($invoicedirectdetails as $key => $value) {

            $goodsCode=Db::name('costtype')->where('type',$value['goodsName'])->where("goodsCode","<>","0")->value('goodsCode');;
            if(empty($goodsCode)){
                $goodsCode='';
            }
            $invoiceDetail[] = "{'goodsName':'{$value['goodsName']}','specType':'{$value['specType']}','unit':'{$value['unit']}','num':'{$value['num']}','price':'{$value['price']}','withTaxFlag':'1','taxRate':'{$value['taxRate']}','tax':'{$value['tax']}','goodsCode':'{$goodsCode}'}";

        }




        //根据小区id查询开票信息
        $communityinfo=Db::table('community')->where('community_id',$community_id)->field("community_name,property_id")->find();
        $propertyinfo=Db::table('property')->where('id',$communityinfo["property_id"])->find();
        $serviceinfo=Db::table('service')->where('id',$propertyinfo["service_id"])->find();

        $remark=$communityinfo["community_name"]." ".$invoicedirect["roomaddress"];
        //判断access_token是否到期
        $second = time()-strtotime($serviceinfo['fp_expires_in']);

        if($second <86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{

            //过期从新获取
            $res = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
            $res=json_decode($res,true);
            if($res["errCode"]=="0"){
                $access_token=$res["fp_access_token"];
            }else{
                return json(["error"=>$res["errormsg"]]);
            }



        }

        $appKey = $serviceinfo["fp_app_key"];
        $appSecret = $serviceinfo["fp_app_secret"];
        $token = $access_token;// please store the token and refresh it before expired
        $taxnum = $serviceinfo["fp_saler_tax_num"];

        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        $method = "nuonuo.electronInvoice.requestBilling"; // change to your method
        $senid = uniqid(); // generate your meaningful senid

        $invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = date("YmdHis").rand(100000,999999);
        $timestmp = time();

        $invoiceDetail = implode(',', $invoiceDetail);
        $buyerName=$invoicedirect["buyerName"];
        $buyerPhone=$invoicedirect["buyerPhone"];


        $buyerTaxNum=$invoicedirect["buyerTaxNum"];
        $buyerTel=$invoicedirect["buyerTel"];
        $buyerAddress=$invoicedirect["buyerAddress"];
        $buyerAccount=$invoicedirect["buyerAccount"];


        $fp_saler_tax_num=$serviceinfo['fp_saler_tax_num'];
        $salerAddress=$serviceinfo['address'];
        $salerTel=$serviceinfo['phone'];
        $salerAddress=$serviceinfo['address'];
        $salerAccount=$serviceinfo['fp_saler_account'];
        $emt="";

        //var_dump($content);
        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"buyerTaxNum\": \"$buyerTaxNum\",
            \"buyerTel\": \"$buyerTel\",
            \"buyerAddress\": \"$buyerAddress\",
            \"buyerAccount\": \"$buyerAccount\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"1\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"remark\": \"$remark\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"http://www.jfzhiwen.com/admin/invoice/callback/\"
            }
        }";

        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);

        //var_dump($result);
        $result = json_decode($result, true);

        //Log::write($result,"invoiceresult");
        //var_dump($result);
        if($result['code'] == 'E0000'){

            $res=Db::table("invoicedirect")->where("id",$id)->update([
                "invoice_serial_num"=>$result['result']['invoiceSerialNum'],
                "invoice_type"=>"1",
                "orderNo"=>$orderNo
            ]);
            return json(["success"=>"开票成功"]);
            return "开票成功";

        }else{
            return json(["error"=>$result['describe']]);

        }
    }

    //蓝票查看
    public function checkInvoice()
    {
        $id = request()->param('id');

        $invoicedirect = Db::table("invoicedirect")->where("id",$id)->find();

        if(!empty($invoicedirect["invoiceFileUrl"])){

            return $this->redirect($invoicedirect['invoiceFileUrl']);
        }
        //return $this->redirect($billinvoice['invoiceFileUrl']);
        //判断房号是否相同
        $communityinfo = (new billService())->communityName($invoicedirect['community_id']);

        $propertyinfo = (new billService())->propertyInfo($communityinfo['property_id']);

        $serviceinfo = (new billService())->serviceInfo($propertyinfo['service_id']);

        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
        if($second < 86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{

            $res = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
            $res=json_decode($res,true);
            if($res["errCode"]=="0"){
                $access_token=$res["fp_access_token"];
            }else{
                return json(["error"=>$res["errormsg"]]);
            }
            //return $access_token;
        }

        $timestmp = time();

        $appKey = $serviceinfo["fp_app_key"];
        $appSecret = $serviceinfo["fp_app_secret"];
        $token = $access_token;// please store the token and refresh it before expired
        $taxnum = $serviceinfo["fp_saler_tax_num"];

        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        $method = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
        $senid = uniqid(); // generate your meaningful senid
        $body = json_encode(
            array(
                "invoiceSerialNum" => array($invoicedirect['invoice_serial_num'])
            )
        );

        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);


        $result = json_decode($result, true);
        //	echo "<pre>";
        //var_dump($result);die;

        if($result['code'] == 'E0000'){
            $info["invoiceCode"]=$result["result"][0]['invoiceCode'];
            $info["invoiceNum"]=$result["result"][0]['invoiceNum'];
            $info["invoiceFileUrl"]=$result["result"][0]['invoiceFileUrl'];
            Db::table("invoicedirect")->where("id",$id)->update($info);


            return $this->redirect($result['result'][0]['invoiceFileUrl']);
        }else{
            return json(['error' => $result['describe']]);
        }
        return $res;
    }
    //再次查看
    public function delivery(){
        if(request()->isPost()){
            $data=request()->post();
            $billinfo = Db::table("invoicedirect")->where("id",$data["id"])->find();

            $communityinfo = (new billService())->communityName($billinfo['community_id']);
            $propertyinfo = (new billService())->propertyInfo($communityinfo['property_id']);

            $serviceinfo = (new billService())->serviceInfo($propertyinfo['service_id']);

            //判断access_token是否到期
            $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
            if($second < 86400){
                //未过期
                $access_token = $serviceinfo['fp_access_token'];
            }else{

                //return $access_token;
                $res = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
                $res=json_decode($res,true);
                if($res["errCode"]=="0"){
                    $access_token=$res["fp_access_token"];
                }else{
                    return json(["error"=>$res["errormsg"]]);
                }

            }
            $phone=$data["phone"];
            $mail=$data["mail"];
            $url = "https://sdk.nuonuo.com/open/v1/services";
            $method = "nuonuo.ElectronInvoice.deliveryInvoice";

            $appKey = $serviceinfo["fp_app_key"];
            $appSecret = $serviceinfo["fp_app_secret"];
            $token = $access_token;// please store the token and refresh it before expired
            $taxnum = $serviceinfo["fp_saler_tax_num"];

            $senid = uniqid(); //唯一标识，由企业自己生成32位随机码
            $body = '{"invoiceSerialNum":["your.voicecode"]}';//API私有请求参数
            $invoiceCode=$billinfo["invoiceCode"];
            $invoiceNum=$billinfo["invoiceNum"];
            $body="{
                  \"mail\": \"$mail\",
                  \"phone\": \"$phone\",
                  \"taxnum\": \"$taxnum\",
                  \"invoiceCode\": \"$invoiceCode\",
                  \"invoiceNum\": \"$invoiceNum\"
                }";
            $res = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
            $result = json_decode($res, true);

            if($result['code'] == 'E0000'){
//
                return "信息推送成功";
            }else{
                return json(['error' => $result['describe']]);
            }
        }else{
            $id=request()->get("id");

            $invoiceinfo = Db::table("invoicedirect")->where("id",$id)->find();
            View::assign("info",$invoiceinfo);
            return View::fetch();
        }

    }
    //发票开具
    public function invoicefilling(){
        if(request()->isPost()){
            $info=request()->post("data");
            $info=html_entity_decode($info);
            $info=json_decode($info,true);

            $invoicedirect['roomaddress']=$info["roomaddress"];
            $invoicedirect['community_id']=$info["community_id"];
            $invoicedirect['buyerName']=$info["buyerName"];
            $invoicedirect['buyerPhone']=$info["buyerPhone"];
            $invoicedirect['buyerTaxNum']=$info["buyerTaxNum"];
            $invoicedirect['buyerTel']=$info["buyerTel"];
            $invoicedirect['buyerAddress']=$info["buyerAddress"];
            $invoicedirect['buyerAccount']=$info["buyerAccount"];

            $invoiceDetails=$info["invoiceDetails"];

            Db::startTrans();
            $pay_money=0;
            try {
                $id=Db::table('invoicedirect')->insertGetId($invoicedirect);
                foreach ($invoiceDetails as $value){
                    $tax=round($value["price"]*$value["num"]*$value["taxRate"],2);
                    $pay_money=$pay_money+round($value["price"]*$value["num"],2);
                    $value["tax"]=$tax;
                    $value["invoicedirect_id"]=$id;
                    Db::table('invoicedirectdetails')->insert($value);
                }
                Db::table('invoicedirect')->where("id",$id)->update([
                    "pay_money"=>$pay_money
                ]);
                // 提交事务
                Db::commit();
                return json(["errorCode"=>"0"]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(["errorCode"=>"error","errmsg"=>$e->getMessage()]);
            }

        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $where['community_id'] = array('in',$com['community_id']);
            $communitylist = (new roominfoService())->communityList($where);
            View::assign('communitylist',$communitylist);

            $costtype=Db::table("costtype")->distinct(true)->field("type")->where("goodsCode","<>","0")->select()->toArray();
            View::assign("costtype",$costtype);
            //return View::fetch("invoice_filling");
            return View::fetch("index");
        }

    }



    public function details(){
        $id = request()->param('id');

        $detailsList = Db::table("invoicedirectdetails")->where("invoicedirect_id",$id)->select()->toArray();

        View::assign("detailsList",$detailsList);
        return View::fetch();
    }

    //当access_token超时时，获取access_token
    public function accessToken($client_id,$client_secret){
        $res = Api::getMerchantToken($client_id, $client_secret);
        $tmpInfo = json_decode($res);


        if(property_exists($tmpInfo,'error')){
            //var_dump($tmpInfo);die;
            //return $tmpInfo;
            return json_encode(["errCode"=>"error","errormsg"=>$tmpInfo->error_description]);
            return $tmpInfo;
            $this->error($tmpInfo->error.',access_token获取失败');
        }
        $data['fp_access_token'] = $tmpInfo->access_token;//获取access_token
        $data['fp_expires_in'] = date('Y-m-d H:i:s',time());
        $data['id'] = (new billService())->serviceFpAppKey($client_id);
        // 存储access_token

        $result = (new billService())->serviceUpdate($data);
        return json_encode(["errCode"=>"0","fp_access_token"=>$data['fp_access_token']]);
        return $data['fp_access_token'];
        // $tmpInfo = '{"access_token":"10ffd45208fb4464aa6fee00vthjozss","expires_in":86400}';

    }
}